package linker.window;

import linker.account.ManageAccount;

import java.awt.AWTEvent;
import java.awt.Dimension;
import java.awt.event.AWTEventListener;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JFrame;

/**
 * 
 * @version linker 0.93
 * @author Jianfeng jianfeng.linker@gmail.com
 * 
 */

public class WindowSaver implements AWTEventListener {

	private static WindowSaver windowSaver;

	private static String path = ManageAccount.getConfigPath() + "windowConfig";

	public static WindowSaver getWindowSaver() {
		if (windowSaver == null)
			windowSaver = new WindowSaver();

		return windowSaver;
	}

	public void eventDispatched(AWTEvent e) {
		try {
			if (e.getID() == WindowEvent.WINDOW_OPENED) {
				ComponentEvent cev = (ComponentEvent) e;
				if (cev.getComponent() instanceof JFrame) {
					JFrame frame = (JFrame) cev.getComponent();
					loadSettings(frame);
				}
			}

			if (e.getID() == WindowEvent.WINDOW_DEACTIVATED) {
				ComponentEvent cev = (ComponentEvent) e;
				if (cev.getComponent() instanceof JFrame) {
					JFrame frame = (JFrame) cev.getComponent();
					saveSettings(frame);
				}
			}

		} catch (Exception ee) {
			ee.printStackTrace();
		}
	}

	public void loadSettings(JFrame frame) throws IOException {
		Properties settings = new Properties();

		try {
			settings.load(new FileInputStream(path));
		} catch (FileNotFoundException fnfe) {
			settings.store(new FileOutputStream(path), "Window settings");
		}

		String name = frame.getName();
		int x = getInt(settings, name + ".x", -1);
		int y = getInt(settings, name + ".y", -1);
		int w = getInt(settings, name + ".w", -1);
		int h = getInt(settings, name + ".h", -1);

		if (x != -1 && y != -1)
			frame.setLocation(x, y);
		if (w != -1 && h != -1)
			frame.setSize(new Dimension(w, h));

		frame.validate();
	}

	private int getInt(Properties settings, String name, int i) {
		String v = settings.getProperty(name);
		if (v == null) {
			return i;
		}

		return Integer.parseInt(v);
	}

	public static void saveSettings(JFrame frame) throws IOException {
		Properties settings = new Properties();
		String name = frame.getName();

		try {
			settings.load(new FileInputStream(path));
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		}

		settings.put(name + ".x", "" + frame.getX());
		settings.put(name + ".y", "" + frame.getY());
		settings.put(name + ".w", "" + frame.getWidth());
		settings.put(name + ".h", "" + frame.getHeight());

		settings.store(new FileOutputStream(path), null);
	}
}
